import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateAccountDto } from '../dto/account/create-account.dto';
import { Account } from '../entities/account.entity';
import { ResMsg } from 'src/utils/constant';
import { UpdateAccountDto } from '../dto/account/update-account.dto';

@Injectable()
export class AccountService {
  constructor(
    @InjectRepository(Account, 'shop')
    private readonly accountRepository: Repository<Account>,
  ) {}

  async create(createAccountDto: CreateAccountDto) {
    try {
      // const pwdCrypt = bcrypt.hashSync(createUserDto.password, 10);
      const row = createAccountDto;
      delete row.pwdRepeat;
      // row.password = pwdCrypt;
      const account = new Account(row);

      const result = await this.accountRepository.save(account);
      if (result) {
        return ResMsg.Success;
      }
      return ResMsg.Fail;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.accountRepository.findOneBy({
        id,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  // 根据用户名查询
  async findUser(username: string) {
    try {
      const user = await this.accountRepository
        .createQueryBuilder('admin_account')
        .addSelect('admin_account.password') // 返回密码
        .where('admin_account.account_name = :accountName', {
          accountName: username,
        })
        .getOne();

      return user;
    } catch (e) {
      throw new ServiceUnavailableException('sql 异常');
    }
  }

  async update(id: number, updateAccountDto: UpdateAccountDto) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = new Account({
          ...dbRow,
          ...updateAccountDto,
        });
        const result = this.accountRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          isDelete: -1,
        };
        const result = this.accountRepository.save(data);
        if (result) {
          return '注销成功';
        }
        return '注销失败';
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
